<template>
  <div ref="canvas"></div>
</template>

<script lang="ts" setup>
import * as THREE from "three";
import { GUI } from "three/examples/jsm/libs/lil-gui.module.min.js";
import Stats from "three/examples/jsm/libs/stats.module";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import {ref, onMounted, render} from "vue";
import {ColladaLoader} from "three/examples/jsm/loaders/ColladaLoader";

const canvas = ref<any>();

const scene = new THREE.Scene();

const renderer = new THREE.WebGLRenderer({ antialias : true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x000000);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;

const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight);
camera.position.set(35, 35, 35);
camera.lookAt(0, 45, 0);

const orbitControl = new OrbitControls(camera, renderer.domElement);
orbitControl.update();

const stat = Stats();

const keyLight = new THREE.SpotLight(0xffffff);
keyLight.position.set(0, 80, 80);
keyLight.intensity = 2;
keyLight.lookAt(new THREE.Vector3(0, 15, 0));
keyLight.castShadow = true;
keyLight.shadow.mapSize.height = 4096;
keyLight.shadow.mapSize.width = 4096;
scene.add(keyLight);

const backlight1 = new THREE.SpotLight(0xaaaaaa);
backlight1.position.set(150, 40, -20);
backlight1.intensity = 0.5;
backlight1.lookAt(new THREE.Vector3(0, 15, 0));
scene.add(backlight1);

const backlight2 = new THREE.SpotLight(0xaaaaaa);
backlight2.position.set(-150, 40, -20);
backlight2.intensity = 0.5;
backlight2.lookAt(new THREE.Vector3(0, 15, 0));
scene.add(backlight2);

const doRender = () => {
  stat.update();

  requestAnimationFrame(doRender);
  renderer.render(scene, camera);
};

const render = () => {
  canvas.value.appendChild(stat.domElement);
  canvas.value.appendChild(renderer.domElement);

  doRender();
};

new ColladaLoader()
    .load(
        new URL("@/assets/models/medieval/Medieval_building.DAE", import.meta.url).href,
        (obj) => {
          const sceneGroup = obj.scene;
          sceneGroup.children.forEach((child) => {
            if (child instanceof THREE.Mesh) {
              child.receiveShadow = true;
              child.castShadow = true;
            } else {
              // remove any lighting sources from the model
              // sceneGroup.remove(child);
            }
          });

          // correctly scale and position the model
          sceneGroup.rotation.z = 0.5 * Math.PI;
          sceneGroup.scale.set(8, 8, 8);

          scene.add(sceneGroup);
          render();
        }
    )

</script>
